import base64
import json
import os
import time

import pymysql
from django.http import HttpResponse
from django.shortcuts import render


def face_collection(request):
    return render(request, 'faceCollection.html')


def face_collection_input(request):
    if request.method == 'POST':
        data = request.body.decode('utf-8')
        jsonData = json.loads(data)
        imgData = base64.b64decode(jsonData['image_base64'])
        cardNum = jsonData['userCardNum']
        # 查询是否是小区住户
        isHousehold = queryHouseholdByCardNum(cardNum)
        print(isHousehold)
        # 如果没查询出结果，说明当前人员不是小区住户，不能录入
        if isHousehold is None:
            return HttpResponse(
                json.dumps({'code': 505, 'message': '该人员不是小区住户，不能录入人脸信息！', 'data': None}),
                content_type='application/json')
        # 查询出结果，说明是小区住户，可以录入人脸
        # 设置录入人脸图片的名字
        timestamp = int(time.time() * 1000)  # 获取当前时间戳
        filename = f"{isHousehold[1]}-{isHousehold[0]}-{timestamp}"
        # filename = isHousehold[1] + "-" + str(isHousehold[0])
        file_path = f'D:/Django/Face_licensePlate_recognition_django/face_images/{filename}.jpg'
        # 删除旧的照片（如果存在),使该用户在文件夹中只保存最新录入的照片
        old_photo_path = isHousehold[4]
        print(old_photo_path)
        if old_photo_path and os.path.exists(old_photo_path):
            os.remove(old_photo_path)
        # 将录入的人脸存入目标文件夹下
        with open(file_path, 'wb') as file:
            file.write(imgData)
        # 将人脸的图片地址存入数据库中
        res = saveHouseholderFace(file_path, isHousehold[0])
        print(res)
        if res:
            return HttpResponse(json.dumps({'code': 200, 'message': '人脸录入成功！！', 'data': None}),
                                content_type='application/json')
        else:
            return HttpResponse(json.dumps({'code': 500, 'message': '人脸录入失败！', 'data': None}),
                                content_type='application/json')


def queryHouseholdByCardNum(cardNum):
    # 连接数据库
    con = pymysql.Connect(
        host="localhost",
        user="root",
        passwd="root",
        database="property_management_system",
        charset="utf8"
    )
    cursor = con.cursor()
    # 编写sql代码
    sql = "select * from householders where householder_card=%s"
    # 执行sql，并传递参数
    cursor.execute(sql, (cardNum,))
    # 获取单个记录
    result = cursor.fetchone()
    cursor.close()
    con.close()
    return result


def saveHouseholderFace(face_path, householderID):
    # 连接数据库
    con = pymysql.Connect(
        host="localhost",
        user="root",
        passwd="root",
        database="property_management_system",
        charset="utf8"
    )
    cursor = con.cursor()
    try:
        # 编写sql代码
        sql = "UPDATE householders SET householder_photo = %s WHERE householder_id = %s"
        # 执行sql，并传递参数
        cursor.execute(sql, (face_path, householderID))
        # 返回受影响的行数
        num = cursor.rowcount
        result = False
        if num > 0:
            result = True
        # 提交事务
        con.commit()
    except Exception as e:
        # 如果有异常发生，回滚事务
        con.rollback()
        print(f"An error occurred: {e}")
        result = False
    finally:
        # 关闭游标
        cursor.close()
        # 关闭连接
        con.close()

    return result
